package merge_sort;

public class sortArray {
    int[] temp;

    public int[] sortArray(int[] nums) {
        temp = new int[nums.length];
        mergeSort(nums,0,nums.length-1);
        return nums;
    }
    public void mergeSort(int[] nums,int left,int right) {
        if(left >= right) return;

        //确定中间点
        int mid = (right+left)/2;

        //根据中间点分成左右部分，分别进行排序[left,mid][mid+1,right]
        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);

        //合并两个有序数组
        int cur1=left,cur2=mid+1,i=0;
        while(cur1 <= mid && cur2 <= right) {
            temp[i++] = nums[cur1] <= nums[cur2] ? nums[cur1++]:nums[cur2++];
        }
        //继续处理未完成的数组
        while(cur1 <= mid) temp[i++] = nums[cur1++];
        while(cur2 <= right) temp[i++] = nums[cur2++];

        //还原
        for(i=left;i<=right;i++) {
            nums[i] = temp[i-left];
        }
    }
}
